const User = require('../models/userModel');
const db = require('../config/db');

const getUserById = (req, res) => {
  const { id } = req.params;
  User.findById(id, function(err, user) {
    if (err || !user) {
      return res.status(404).json({ error: 'User not found' });
    }
    res.json(user);
  });
};

const addUser = (req, res) => {
  const { username, password } = req.body;
  User.create(username, password, function(err) {
    if (err) {
      return res.status(400).json({ error: 'Username already exists' });
    }
    res.status(201).json({ message: 'User added successfully' });
  });
};

const getUnreadMessages = (req, res) => {
  const { userId } = req.params;

  db.get(
    `SELECT COUNT(*) AS unreadCount FROM messages 
     WHERE receiver_id = ? AND is_read = FALSE`,
    [userId],
    (err, row) => {
      if (err) {
        return res.status(500).json({ error: 'Database error' });
      }
      res.json({ unreadCount: row.unreadCount });
    }
  );
};

module.exports = { getUserById, addUser, getUnreadMessages }; 